<!--
文件上传组件
文件上传列表默认存在,并且在使用时没有上传按钮,而是
注意尽量添加accept属性来指定文件类型
关于beforeUpload,返回值需要为一个promise对象或true/false.
-->
<template>
  <div class="z-upload">
    <div class="z-upload-label">
      <strong>{{ title }}</strong>
    </div>
    <div class="z-upload-content"
         v-loading="loading"
         :element-loading-text="loadingText"
         element-loading-spinner="el-icon-loading"
         element-loading-background="rgba(0, 0, 0, 0.1)"
    >
      <div :title="file.fileName" :class="'z-upload-item' + (selectDisabled ? ' is_disabled':'')" v-if="showFileList"
           v-for="(file, index) in fileList"
           @click.stop="preview(file,index)"
           @mouseenter="handleMouseEnter"
           @mouseleave="handleMouseLeave"
           style="line-height: 40px"
      >
        <a style="">{{ file.fileName }}</a>
        <i class="el-icon-circle-check"
           style="color: #67c23a; position: absolute; right: 0px;margin: auto;; padding-right: 5px"
           @click.stop="handleDel(index)"
           v-if="!selectDisabled"
        ></i>
      </div>
      <div class="z-upload-item" v-if="fileList.length < limit && !selectDisabled" @click="handleSelectFile(-1)">
        <i class="el-icon-plus avatar-uploader-icon" style=""></i>
      </div>
      <div class="tip" v-if="$slots.default">
        <slot/>
      </div>
    </div>
    <input type="file" style="display: none" :accept="accept" ref="z-input-upload" @change="handleChange"/>
    <el-dialog :visible.sync="dialog.visible" append-to-body close-on-click-modal close-on-press-escape lock-scroll>
      <template #title style="margin-left: 30px">
        <el-tooltip effect="dark" content="下载" placement="top">
          <el-button icon="el-icon-download" :disabled="false" @click="download()" type="primary" plain circle/>
        </el-tooltip>
        <el-tooltip effect="dark" content="删除" placement="top" v-if="!selectDisabled">
          <el-button icon="el-icon-delete" :disabled="false" type="danger" @click="handleDel()" plain circle/>
        </el-tooltip>
      </template>
      <!--      <div style="max-height: 500px;overflow: auto">-->
      <img width="100%" :src="dialog.url" v-if="dialog.fileType === 'image'" style="object-fit: scale-down" alt=""/>
      <video width="100%" :src="dialog.url" controls v-else-if="dialog.fileType === 'video'" alt=""/>
      <p v-else>{{ dialog.fileName }}</p>
      <!--      </div>-->
      <template #footer>
        <el-button @click="dialog.visible = false" :disabled="false">返回</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>


// 文件类型与文件后缀的映射
const extensionTypeMap = {
  'jpg': 'image',
  'jpeg': 'image',
  'png': 'image',
  'gif': 'image',
  'bmp': 'image',

  'mp4': 'video',
  'mkv': 'video',
  'avi': 'video',
  'mov': 'video',
  'wmv': 'video',
  'flv': 'video',

  'mp3': 'audio',
  'wav': 'audio',
  'ogg': 'audio',
  'aac': 'audio',
  'm4a': 'audio',

  // ... 更多文件类型的映射
};
import fileApi from '@/api/file/fileApi.js'
import emitter from '@/mixins/emitter.js'
export default {
  name: "z-upload",
  model: {
    prop: 'fileList',
    event: 'change'
  },
  mixins: [emitter],
  // 依赖注入,这里用于配合el-form的disabled属性
  inject: {
    elForm: {
      default: ''
    }
  },
  props: {
    // 是否显示文件上传列表
    showFileList: {
      type: Boolean,
      default() {
        return true;
      }
    },
    // 上传的文件类型,可选attachment(附件),picture(图片),video(视频)
    listType: {
      type: String,
      validator(value) {
        return ['attachment', 'picture', 'video'].includes(value);
      },
      default: 'attachment'
    },
    // 文件上传的地址,一般情况下无需修改
    action: {
      type: String,
      default() {
        return fileApi.uploadUrl
      }
    },
    // 这是文件上传的标题
    title: {
      type: String,
      default() {
        return ''
      }
    },
    // 最大文件上传数量,默认为1.如果超出那么不再显示文件上传的按钮
    limit: {
      default: Infinity,
      validator(value) {
        return typeof value === 'number' && value > 0
      }
    },
    // 文件列表,对应后端返回的fileInfoVo或fileInfoVos
    fileList: {
      type: Array,
      default() {
        return []
      }
    },
    // 上传的文件类型,默认任意文件
    accept: {
      type: String,
      default() {
        return '*'
      }
    },
    // 上传前调用的钩子
    beforeUpload: {
      type: Function,
    },
    beforeDel: {
      type: Function,
    },
    onSuccess: {
      type: Function,
    },
    onError: {
      type: Function,
    },
    // 文件上传时显示的文本
    loadingText: {
      type: String,
      default: '文件上传中...'
    },
    disabled: {
      type: Boolean,
      default: false
    },
    // 是否加入到表单验证中
    validateEvent: {
      type: Boolean,
      default: true
    },
  },
  watch: {
    // 监听fileList,用于配合el-form进行表单验证
    fileList: {
      handler(value) {
        if (this.validateEvent) {
          this.dispatch('ElFormItem', 'el.form.change', [value]);
        }
      },
      deep: true
    }
  },
  data() {
    return {
      loading: false,
      // 用于记录触发文件上传时点击的是哪一个文件列表(-1为上传按钮)
      selectedIndex: -1,
      dialog: {
        visible: false,
        url: '',
        fileType: '',
        fileName: ''
      },
    }
  },
  computed: {
    selectDisabled() {
      return this.disabled || (this.elForm || {}).disabled;
    }
  },
  methods: {
    // 文件上传选择文件后的change事件
    handleChange(event) {
      let {target} = event
      let file = target.files[0]
      // 如果file为null,那么说明没有选取文件,那么无需上传.
      if (!file) {
        return
      }
      this.$emit('change', this.fileList)
      // 注意,每次文件上传的操作时都需要将input赋为空,因为监听的是change事件,避免选择反复同一文件不能触发上传.
      this.$refs['z-input-upload'].value = null
      this.upload(file)
    },
    // 下载某文件
    download(index = this.selectedIndex) {
      this.$rq.downloadFileStream(this.fileList[index].path, null, this.fileList[index].fileName)
    },
    // 触发文件上传
    handleSelectFile(index) {
      this.selectedIndex = index
      this.$refs['z-input-upload'].click()
      // 如果是被禁用了,那么点击后触发下载
      // if (this.disabled) {
      //   this.download(index)
      // } else {
      //   this.$refs['z-input-upload'].click()
      // }
    },
    upload(file) {
      // 如果没有上传前的调用,直接上传
      if (!this.beforeUpload) {
        this.post(file)
        return
      }
      // 如果上传前的调用,那么先调用该方法
      const before = this.beforeUpload(file, this.selectedIndex, this.fileList);
      // 如果是异步方法,那就
      if (before && before.then) {
        before.then(_ => {
          this.post(file)
        })
      } else if (before !== false) {
        // 不是异步方法且返回不为false,直接调用
        this.post(file)
      }
    },
    // 文件上传
    post(file) {
      this.loading = true
      this.$rq.httpPostForm(this.action, {file}).then(res => {
        // 即如果是点击的+按钮
        if (this.selectedIndex === -1) {
          this.fileList.push(res.data)
        } else {
          // 原本是点击文件后的会将该文件替换,现在这部分逻辑不会走了
          this.fileList.splice(this.selectedIndex, 1, res.data)
        }
        if (this.onSuccess) {
          this.onSuccess()
        }
      }, err => {
        console.error(err)
        if (this.onError) {
          this.onError()
        }
      }).finally(_ => {
        this.loading = false
      })
    },
    handleMouseEnter($event) {
      let icon = $event.target.querySelector('i[class^="el-icon-"]')
      if(icon != null){
        icon.className = 'el-icon-close'
      }
    },
    handleMouseLeave($event) {
      let icon = $event.target.querySelector('i[class^="el-icon-"]')
      if(icon != null){
        icon.className = 'el-icon-circle-check'
      }
    },
    // 删除文件
    handleDel(index = this.selectedIndex) {
      if (this.beforeDel) {
        let before = this.beforeDel(this.fileList[index], this.selectedIndex, this.fileList)
      }
      this.fileList.splice(index, 1)
      // 可能是在dialog删除的,所以这里判断一下
      if (this.dialog.visible) {
        this.dialog.visible = false
      }
    },
    // 预览
    preview(file, index) {
      this.selectedIndex = index
      const {path, fileType, fileName} = this.fileList[index]
      this.dialog.url = path
      this.dialog.fileType = extensionTypeMap[fileType]
      this.dialog.visible = true
      this.dialog.fileName = fileName
    }
  },
  mounted() {
  }

}
</script>

<style lang="scss" scoped>

.z-upload {
  position: relative;
}

[class*=" el-icon-"], [class^=el-icon-] {
  line-height: inherit;
}

.z-upload-content {
  box-sizing: border-box;
  width: 100%;
}

.z-upload-item {
  /* 这三项属性实现文件名过长以省略号的形式省略*/
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  cursor: pointer;
  position: relative;
  height: 40px;
  padding-right: 14px;
  background-color: #F5F7FA;
  border: 1px solid #E4E7ED;
  border-radius: 4px;
  padding-left: 10px;
  box-sizing: border-box;

  &:hover {
    color: #409eff;
    background-color: #f1f1f1;
  }
}

.z-upload-label {

}

.is_disabled {
  background-color: #F5F7FA;
  border-color: #E4E7ED;
  color: #C0C4CC;
  /*cursor: not-allowed;*/
}

.z-upload__tip:before {
  content: '*';
  color: #fd0000;
}

// 底部提示的样式
.tip {
  font-size: 12px;
  line-height: 20px;

  &::before {
    content: '*';
    color: #F56C6C;
    margin-right: 4px;
  }
}
</style>
